package b2d;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.FixtureDef;
import org.jbox2d.dynamics.World;
public class W2d {
	private final int m_physScale = 30;
	public final int m_velocityIterations = 10;
	public final int m_positionIterations = 10;
	public final float m_timeStep = 1.0f/30.0f;
	
	private World world;
	
	public Body body;
	public W2d(){
		Vec2 gravity = new Vec2(0, 10);
		boolean sleep = true;
		world = new World(gravity);
		world.setAllowSleep(sleep);
		
		// Create border of boxes
		PolygonShape wall = new PolygonShape();
		BodyDef wallBd = new BodyDef();
		Body wallB;
		wall.setAsBox(50 / m_physScale, 300/m_physScale);
		// Left
		wallBd.position.set(10 / m_physScale, 300 / m_physScale);
		wallB = world.createBody(wallBd);
		wallB.createFixture(wall, 0);
		// Right
		wallBd.position.set((800 - 10) / m_physScale, 300 / m_physScale);
		wallB = world.createBody(wallBd);
		wallB.createFixture(wall, 0);
		// Top
		wall.setAsBox(400/m_physScale, 50/m_physScale);
		wallBd.position.set(400 / m_physScale, 10 / m_physScale);
		wallB = world.createBody(wallBd);
		wallB.createFixture(wall, 0);
		// Bottom
		wallBd.position.set(400 / m_physScale, (600 - 10) / m_physScale);
		wallB = world.createBody(wallBd);
		wallB.createFixture(wall, 0);
		
		body = addBall2Word();
	}
	
	public Body addBall2Word(){
		CircleShape cd;
		BodyDef bd;
		Body body;
		FixtureDef fd;
		cd = new CircleShape();
		cd.setRadius(15 / m_physScale);
		fd = new FixtureDef();
		fd.shape = cd;
		fd.friction = 10;
		fd.restitution = 0.5f;
		fd.density = 1.0f;
		fd.filter.groupIndex = -1;
		bd = new BodyDef();
		bd.type = BodyType.DYNAMIC;
		// Position in world space
		bd.position.set(100f, 100f);
		body = world.createBody(bd);
		body.createFixture(fd);
		return body;
	}
	
	public void Update(){
		// Update physics
		world.step(m_timeStep, m_velocityIterations, m_positionIterations);
		world.clearForces();
		// Render
		world.drawDebugData();
	}
}
